package cn.dankal.flyaudio.personal

import android.view.View
import android.widget.TextView
import api.UserServiceFactory
import butterknife.OnClick
import cn.dankal.basiclib.DKUserManager
import cn.dankal.basiclib.base.activity.BaseActivity
import cn.dankal.basiclib.common.sms.SmsCodeImpl
import cn.dankal.basiclib.pojo.PhoneOrEmailIsExistBean
import cn.dankal.basiclib.pojo.SmSReturnBean
import cn.dankal.basiclib.protocol.LoginProtocol
import cn.dankal.basiclib.rx.AbstractDialogSubscriber
import cn.dankal.basiclib.rx.AbstractSubscriber
import cn.dankal.basiclib.util.StringUtil
import cn.dankal.basiclib.util.ToastUtils
import cn.dankal.basiclib.widget.titlebar.SingleTextTitle
import cn.dankal.business.pojo.ReasonBean
import cn.dankal.business.Constants
import cn.dankal.flyaudio.R
import cn.dankal.flyaudio.login.SetLoginPasswdActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import kotlinx.android.synthetic.main.activity_getcode.*
import java.util.HashMap

@Route(path = LoginProtocol.UNBIND_BIND_PHONE)
class UnbindBind_PhoneActivity : BaseActivity() {
    lateinit var phone: String
    var smsCode = SmsCodeImpl(this)
    lateinit var singleTextTitle: SingleTextTitle

    override fun getLayoutId(): Int {
        return R.layout.activity_getcode
    }

    override fun initComponents() {

        if (StringUtil.isValid(DKUserManager.getUserInfo().phone)) {

            singleTextTitle = SingleTextTitle("解除绑定")
            tv_tips.setText("已绑定手机号")
            et_mobile.setText(DKUserManager.getUserInfo().phone)

        } else {
            singleTextTitle = SingleTextTitle("绑定手机号")
            tv_tips.setText("手机号")
            et_mobile.isEnabled = true
        }
        addTitleBar(singleTextTitle)

    }


    @OnClick(R.id.bt_code, R.id.bt_next)
    fun onViewClicked(view: View) {
        when (view.id) {
            R.id.bt_code -> {
                phone = et_mobile.text.toString()
                smsCode.getCode(phone, bt_code, Constants.CheckType.Phone.states.toString())
            }
            R.id.bt_next -> {
                phone = et_mobile.text.toString()

                var text = singleTextTitle.titleView.findViewById<TextView>(R.id.tv_title).text.toString()

                if (!StringUtil.isValid(phone)) {
                    ToastUtils.showShort("请输入手机号码")
                    return
                }
                val code = et_code.getText().toString()
                if (!StringUtil.isValid(code)) {
                    ToastUtils.showShort("请输入验证码")
                    return
                }

                if (text.equals("解除绑定")) {
                    validaCode(code)
                    return
                }
                isBindPhone(phone, code, text)
            }
        }
    }

    private fun bindPhone(code: String) {
        /**
         * {
        "code": "验证码",
        "fgToken": "飞歌token",
        "newPhone": "新手机号码",
        "userId": "飞歌userId"
        }
         */
        var hashMap = HashMap<String, String>(4)
        hashMap.put("code", code)
        hashMap.put("fgToken", DKUserManager.getUserInfo().fgToken)
        hashMap.put("newPhone", phone)
        hashMap.put("userId", DKUserManager.getUserInfo().id)
        UserServiceFactory.updateUserPhone(hashMap).subscribe(object : AbstractSubscriber<ReasonBean>(this) {
            override fun onNext(t: ReasonBean) {
                DKUserManager.getUserInfo().phone = phone
                DKUserManager.updateUserInfo(DKUserManager.getUserInfo())
                finish()
            }

        })
    }

    /**
     * 判断当前手机号是否存在
     */
    private fun isBindPhone(phone: String, code: String, text: String) {
        UserServiceFactory.phoneOrEmailIsExist(phone, 0).subscribe(object : AbstractSubscriber<PhoneOrEmailIsExistBean>(this) {
            override fun onNext(t: PhoneOrEmailIsExistBean) {
                when (t.reason.toString()) {
                    "10001" -> {
                        ToastUtils.showShort("此手机号已存在，暂不能绑定！")
                    }
                    "20001" -> {
                        if (text.equals("绑定新手机号码")) {
                            bindPhone(code)
                            return
                        }
                        validaCodeReigster(phone!!, code)
                    }
                }
            }
        })
    }


    /**
     * 检查验证码
     */
    private fun validaCodeReigster(phone: String, code: String) {
        val map = HashMap<String, String>(2)
        map.put(Constants.PHONE, phone)
        map.put(Constants.CODE, code)
        ARouter.getInstance().build(LoginProtocol.SET_LOGIN_PASSWD)
                .withString(SetLoginPasswdActivity.MOBLIE, phone)
                .withString(Constants.CODE,code)
                .withString(Constants.TYPE, intent.getStringExtra(Constants.TYPE))
                .navigation()
//        UserServiceFactory.registerSkip(map)
//                .subscribe(object : AbstractDialogSubscriber<SmSReturnBean>(this) {
//                    override fun onNext(t: SmSReturnBean) {
//                        /*   val userResponseBody = UserResponseBody()
//                        val tokenBean = UserResponseBody.TokenBean()
//                        tokenBean.token = userInfoBean.getAccessToken()
//                        userResponseBody.token = tokenBean
//                        DKUserManager.saveUserInfo(userResponseBody)*/
//
//                        ARouter.getInstance().build(LoginProtocol.SET_LOGIN_PASSWD)
//                                .withString(SetLoginPasswdActivity.MOBLIE, phone)
//                                .withString(Constants.UUID, t.id)
//                                .withString(Constants.CODE,code)
//                                .withString(Constants.TYPE, intent.getStringExtra(Constants.TYPE))
//                                .navigation()
//                        finish()
//                    }
//
//                })
    }


    private fun validaCode(code: String) {
//        "code": "验证码",
//        "fgToken": "飞歌token",
//        "newPhone": "新手机号码",
//        "userId": "飞歌userId"
        UserServiceFactory.validationCode(phone, "0", code)
                .subscribe(object : AbstractDialogSubscriber<ReasonBean>(this) {
                    override fun onNext(checkCode: ReasonBean) {
                        showBindPhone()
                    }
                })
    }


    private fun showBindPhone() {
        smsCode.release(bt_code)
        smsCode.onDestory()
        et_mobile.isEnabled = true
        et_mobile.setText("")
        et_code.setText("")
        singleTextTitle.titleView.findViewById<TextView>(R.id.tv_title).text = "绑定新手机号码"
        tv_tips.setText("请输入新手机号")
    }

    override fun onDestroy() {
        super.onDestroy()
        smsCode.onDestory()
    }
}
